package com.example.zhihuhelpapp.adapter;

import android.content.Context;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.example.zhihuhelpapp.R;
import com.example.zhihuhelpapp.api.MySubscribe;
import com.example.zhihuhelpapp.api.RetrofitManager;
import com.example.zhihuhelpapp.bean.AuthorBean;
import com.example.zhihuhelpapp.bean.QuestionBean;
import com.example.zhihuhelpapp.bean.QuestionResultBean;
import com.example.zhihuhelpapp.utils.CoreConstant;
import com.example.zhihuhelpapp.utils.DbUtils;
import com.example.zhihuhelpapp.utils.LogUtils;
import com.example.zhihuhelpapp.utils.SpUtils;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 问题列表Adapter
 */
public class QuestionListAdapter extends CommonAdapter<QuestionBean> {
    private Map<Integer, Integer> rakingMap;
    private Map<Integer, Integer> tempRakingMap;
    private boolean isGetItemRaking = false;

    public QuestionListAdapter(Context context, List<QuestionBean> datas) {
        super(context, R.layout.item_home_question_list, datas);
        rakingMap = new HashMap<>();
        tempRakingMap = new HashMap<>();
    }

    @Override
    protected void convert(ViewHolder holder, QuestionBean questionBean, int position) {
        TextView tv_top_state = holder.getView(R.id.tv_top_state);
        TextView tv_question_title = holder.getView(R.id.tv_question_title);
        TextView tv_my_answer_raking = holder.getView(R.id.tv_my_answer_raking);
        TextView tv_answer_count = holder.getView(R.id.tv_answer_count);
        tv_question_title.setText(mContext.getString(R.string.app_home_question_name, questionBean.getQuestionTitle()));
        tv_answer_count.setText(mContext.getString(R.string.app_home_answer_count, questionBean.getQuestionAnswerCount()));

        tv_top_state.setVisibility(questionBean.isTop() ? View.VISIBLE : View.GONE);

        if (rakingMap.containsKey(position)) {
            tv_my_answer_raking.setText(mContext.getString(R.string.question_answer_raking, rakingMap.get(position)));
        } else {
            tv_my_answer_raking.setText(mContext.getString(R.string.question_answer_raking, questionBean.getAnswerRaking()));
        }

        if (isGetItemRaking || questionBean.getShowRaking() == 1) {
            if (!tempRakingMap.containsKey(position)) {
                getItemApi(position, 0);
            }
        }
    }

    public void setGetItemRaking(boolean getItemRaking) {
        isGetItemRaking = getItemRaking;
        notifyDataSetChanged();
    }

    private void getItemApi(int position, final int page) {
        String nickName = SpUtils.getInstance().get(CoreConstant.SpConstant.KEY_NICK_NAME, "");
        if (TextUtils.isEmpty(nickName)) {
            return;
        }
        if (!tempRakingMap.containsKey(position)) {
            tempRakingMap.put(position, 0);
        }
        RetrofitManager.getInstance()
                .apiService()
                .getQuestionDetail(mDatas.get(position).getQuestionId(), CoreConstant.QUESTION_PAGE_COUNT,
                        CoreConstant.QUESTION_PAGE_COUNT * page)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new MySubscribe<QuestionResultBean>() {
                    @Override
                    public void onNext(QuestionResultBean questionResultBean) {
                        boolean isSuccess = false;
                        if (questionResultBean != null) {
                            QuestionResultBean.PagingBean paging = questionResultBean.getPaging();
                            List<QuestionResultBean.DataBean> dataList = questionResultBean.getData();
                            int totalCount = paging.getTotals();
                            if (dataList != null && dataList.size() > 0) {
                                for (QuestionResultBean.DataBean dataBean : dataList) {
                                    tempRakingMap.put(position, tempRakingMap.get(position) + 1);
                                    AuthorBean author = dataBean.getAuthor();
                                    if (TextUtils.equals(author.getName(), nickName)) {
                                        isSuccess = true;
                                        break;
                                    }
                                }
                            }
                            if (!isSuccess) {
                                // 没有找到，需要再查找下一页
                                if ((page + 1) * CoreConstant.QUESTION_PAGE_COUNT > totalCount) {
                                    // 没有找到
                                    rakingMap.put(position, -1);
                                } else {
                                    getItemApi(position, page + 1);
                                }
                            } else {
                                // 找到了，就刷新数据
                                rakingMap.put(position, tempRakingMap.get(position));
                                mDatas.get(position).setQuestionAnswerCount(totalCount);
                                mDatas.get(position).setAnswerRaking(tempRakingMap.get(position));
                                DbUtils.saveQuestion(mDatas.get(position));
                                notifyDataSetChanged();
                            }

                        } else {
                            LogUtils.i("获取问题详情失败");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        LogUtils.i("获取问题详情异常：" + e.getMessage());
                    }
                });
    }

}
